#include <webx/route.h>
#include <dbentity/T_XG_ROUTE.h>

class GetCgidocList : public webx::ProcessBase
{
protected:
	int process();
	bool checkClient();
};

HTTP_WEBAPP(GetCgidocList)

class CgidocItem
{
public:
	string url;
	string key;
	int enabled;
	string title;
	string folder;
	string remark;

	CgidocItem(CT_XG_ROUTE& tab, JsonElement& data)
	{
		enabled = data["enabled"].asInt();
		remark = data["remark"].asString();
		title = data["path"].asString();

		if (tab.host.val().empty())
		{
			stdx::append(url, "/cgidoc?padding=0px&path=%s", title.c_str());
		}
		else
		{
			stdx::append(url, "/cgidoc?padding=0px&path=%s&host=%s&port=%d", title.c_str(), tab.host.val().c_str(), tab.port.val());
		}

		size_t pos = title.find('@');

		if (pos == string::npos)
		{
			folder = tab.name.val();
		}
		else
		{
			folder = title.substr(pos + 1);
			title = title.substr(0, pos);
		}

		key = folder + ":" + title;
	}
};

int GetCgidocList::process()
{
	int res = 0;
	CT_XG_ROUTE tab;
	set<string> uset;
	vector<CgidocItem> vec;

	param_string(key);

	stdx::tolower(key);

	auto parse = [&](const string& content){
		JsonElement json(content);

		if (json["list"].isArray())
		{
			JsonElement list = json["list"];

			for (auto item : list)
			{
				CgidocItem doc(tab, item);
				const string& path = item["path"].asString();

				if (key.length() > 0 && path.find(key) == string::npos) continue;

				if (doc.title == "execmodule" || doc.title == "tracemodule") continue;

				if (uset.insert(doc.key).second) vec.push_back(doc);
			}
		}
	};

	if (app->getRouteSwitch())
	{
		tab.init(webx::GetDBConnect());

		if (!tab.find("ENABLED>0 AND PROCTIME>0")) return simpleResponse(XG_SYSERR);
		
		while (tab.next()) parse(tab.content.toString());

		tab.close();
	}
	else
	{
		SmartBuffer data;
		HttpRequest request("getcgilist");

		tab.name = app->getName();

		sp<HttpResponse> response = app->getLocaleResult(request);

		if (response) data = response->getResult();

		if (data.str()) parse(data.str());
	}

	std::sort(vec.begin(), vec.end(), [](const CgidocItem& a, const CgidocItem& b){
		return a.key < b.key;
	});

	JsonElement arr = json.addArray("list");

	for (auto& item : vec)
	{
		JsonElement data = arr[res++];

		data["url"] = item.url;
		data["title"] = item.title;
		data["folder"] = item.folder;
		data["remark"] = item.remark;
		data["enabled"] = item.enabled;
	}

	json["code"] = res;
	out << json;

	return XG_OK;
}